const express = require("express"),
  { Server } = require("socket.io"),
  { createServer } = require("http"),
  path = require("path"),
  { QRCode } = require("./utils/qr"),
  app = express(),
  port = 3000,
  cors = require("cors"),
  wsPort = 8080,
  httpServer = createServer(app),
  login = require("./router/login"),
  //引入插件
  vertoken = require("./utils/token"),
  expressJwt = require("express-jwt"),
  user = require("./router/user");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static(path.join(__dirname, "public/www")));
app.use(express.static(path.join(__dirname, "public/images")));
app.use((req, res, next) => {
  let token = req.headers["authorization"];
  if (token == undefined) {
    next();
  } else {
    vertoken
      .getToken(token)
      .then((data) => {
        req.data = data;
        next();
      })
      .catch((err) => {
        next();
      });
  }
});
//验证token是否过期并规定那些路由不需要验证
app.use(
  expressJwt({
    secret: vertoken.jwtScrect,
    // 算法
    algorithms: ["HS256"],
  }).unless({
    path: [
      "/login/code",
      "/login",
      "/user",
      "/user/getSets",
      "/user/inputWinnerList",
      "/user/getWinners",
      "/user/delList",
      "/qr",
    ], //不需要验证的接口名称
  })
);
app.use(function (err, req, res, next) {
  if (err.status == 401) {
    return res.status(401).send("token失效");
    //可以设置返回json 形式  res.json({message:'token失效'})
  }
});
app.use("/login", login);
app.use("/user", user);
app.get("/qr", (req, res) => {
  res.send({ code: 200, data: QRCode });
});
const io = new Server(httpServer, {
  cors: {
    origin: [
      "http://127.0.0.1:5500",
      "http://127.0.0.1:5501",
      "http://localhost:3000",
      "http://localhost:8081",
      "http://leipinp.top",
      "http://www.leiping.top",
    ],
    methods: ["GET", "POST"],
    // allowedHeaders: ["my-custom-header"],
    credentials: true,
  },
});
io.on("connection", (socket) => {
  socket.emit("open", socket.id);
  // console.log(socket.handshake.auth); // prints { token: "abcd" }
  socket.on("disconnect", (v) => {
    console.log(v);
  });
  socket.on("onMsg", (v) => {
    io.sockets.emit("receiveMsg", v);
  });
});
function getIPAdress() {
  var interfaces = require("os").networkInterfaces();
  for (var devName in interfaces) {
    if (!(devName == "以太网" || devName == "WLAN")) continue;
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return alias.address;
      }
    }
  }
}
const ipAdress = getIPAdress();
app.listen(port, () => {
  console.log(
    `app listening at http://localhost:${port}` +
      "\n" +
      `app listening at http://${ipAdress}:${port}`
  );
});
httpServer.listen(wsPort, () => {
  console.log(`ws start ws://${ipAdress}:${wsPort}`);
});
